#!/usr/bin/env python
# -*- mode: python; coding: utf-8; -*-
##--------------------------------------------------------------------------##
##
## Copyright (C) 1998-2003 Markus Oberhumer <markus@oberhumer.com>
## Copyright (C) 2003 Mt. Hood Playing Card Co.
## Copyright (C) 2005-2010 Skomoroh <skomoroh@users.sourceforge.net>
## Copyright (C) 2010-2013 Jeremy Austin-Bardo <tjaustinbardo@gmail.com>
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.
##
##--------------------------------------------------------------------------##
import collections
import shelve


class Persistance(collections.MutableMapping):
    """
    Data file class to hold a set of attributes derived from
    collections.MutableMapping. Includes additional save and load methods that
    enable data persistance.
    """
    __attributes = {}
    _empty_value = ""

    def new(self):
        return self

    def __setitem__(self, index, text):
        """
        object[key] = value
        """
        self.__attributes[str(index)] = text
        self.__attributes.sync()

    def __getitem__(self, index):
        """
        object[key]
        """
        return self.__attributes.get(str(index), self._empty_value)

    def __delitem__(self, index):
        """
        del(object[key])
        """
        if index in self.__attributes:
            del(self.__attributes[str(index)])

    def __len__(self):
        """
        len(object)
        """
        return len(self.__attributes)

    def __iter__(self):
        """
        (k, v) for k, v in object
        """
        return iter(self.__attributes.items())

    def reset(self, index):
        if index in self.__attributes:
            del(self.__attributes[str(index)])
        else:
            self.__attrributes = {}

    def save(self, filename):
        """
        save(self, filename:str) => None
        """
        self.__attributes.close()

    def load(self, filename):
        """
        load(self, filename:str) => None
        """
        self.__attributes = shelve.open(filename, protocol=-1, flag='c')

NOTE_DB = Persistance()